<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="/resource/css/bootstrap-table.min.css" type="text/css">

<!-- Latest compiled and minified JavaScript -->
<script src="/resource/js/bootstrap-table.min.js"></script>
<!-- Latest compiled and minified Locales -->
<script src="/resource/js/bootstrap-table-zh-CN.min.js"></script>


<script>
  let onlineUserCountAndLastPushAt;
  const $table = $('#table')
  $(function () {
    GetOnlineUserCountAndLastPushAt()
    
  })

  //初始化表格
  function initTable() {
    $table.bootstrapTable({
      columns: [
          {
            field: 'name',
            title: '名称',
          }, 
          {
            field: 'agreement',
            title: '协议',
          }, {
            title: '状态',
            formatter: function (value, row, index) {
              if (onlineUserCountAndLastPushAt[row.id] == undefined) {
                return `<span class="badge badge-dot">
                        <i class="bg-warning"></i>
                        <span class="status">离线</span>
                      </span>`
              }else{
                let htmlStr = (onlineUserCountAndLastPushAt[row.id][1] || 0) + " | ";
                if ((Math.floor(new Date().getTime() / 1000) - onlineUserCountAndLastPushAt[row.id][2]) < 300) {
                  htmlStr = htmlStr + `<span class="badge badge-dot">
                        <i class="bg-success"></i>
                        <span class="status">正常</span>
                      </span>`
                }else{
                  htmlStr = htmlStr + `<span class="badge badge-dot">
                        <i class="bg-dark"></i>
                        <span class="status">异常</span>
                      </span>`
                }
                return htmlStr
                

              }
              
            }
          }, {
            field: 'rate',
            title: '倍率',
          }, {
            field: 'updated_at',
            title: '更新时间',
          }, {
            field: 'operate',
            title: '操作',
            width:120,
            events: {
              'click #copy_url': function (e, value, row, index) {
                copy_url(row)
              },
            },
            formatter: function (value, row, index) {
                return `
              <div class="btn-group" role="group" aria-label="Basic example">
                <button id="copy_url" type="button" class="btn btn-twitter btn-icon-only" data-toggle="tooltip" data-placement="left" title="复制URL"><span class="btn-inner--icon"><i class="ni ni-single-copy-04"></i></span></button>
              </div>`;
              
            }
          }
      ], //列
      url: '/user/node',
      method: 'post', //请求方法
      dataType: 'json',//数据格式
      pagination: false, //是否显示页码
      sidePagination: "server",//服务器处理分页
      serverSort: "true",//是否服务器处理排序
      sortName:'id',
      sortOrder:'desc',
      showRefresh: true,  //显示刷新按钮
      showColumns: true, //是否显示列下拉列表按钮
      showFullscreen: true, //是否显示全屏按钮
      responseHandler: function (res) {  //response数据处理

        return {
          "rows": res.data.data,
        };
      },

      //搜索
      queryParams: function (x) {
        $("select[data-function='search']").each(function (i, domEle) {
          x[$(domEle).attr("name")] = domEle.value
        })

        $("input[data-function='search']").each(function (i, domEle) {
          const bindingDomID = $(domEle).attr("data-select-binding")
          if (bindingDomID != undefined) {
            x[$(bindingDomID).attr("name")] = $(bindingDomID).val()
          }
          x[$(domEle).attr("name")] = domEle.value
        })


        return x
      },
      onLoadSuccess: function() {
        $('[data-toggle="tooltip"]').tooltip()
      },
      formatNoMatches: function(){
        return "当前订阅没有节点";
      },

    })
  }

  //获取所有服务器当前在线用户数量和服务器最后提交时间
  function GetOnlineUserCountAndLastPushAt() {
    if (onlineUserCountAndLastPushAt == undefined) {
      $.ajax({
        type: "POST",
        url: "/user/node/online_user_count_and_last_push_at",
        dataType: "json",
        success: function (data) {
          if (data.code == 0) {
            onlineUserCountAndLastPushAt = data.data.data
            initTable()
          } else {
            notify('danger', data.message)
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          console.log(errorThrown)
          notify('danger', errorThrown)
        },
        complete: function () {//不管成功还是失败 都会进这个函数
          
        }
      });
    }
    
  }


  function copy_url(params) {
    var serviceJson = JSON.parse(params.service_json);
    var url = "";
    switch (params.agreement) {
      case "v2ray/vmess":
        var d = {
          "v":    "2",
					"add":  params.host, //链接地址
					"ps":   params.name, //名字
					"port": params.port, //端口
					"id":   "{{.user.Uuid}}",    //uuid
					"aid":  "0",
					"net":  serviceJson["net"],
					"type": serviceJson["type"],
					"tls":  serviceJson["tls"],
					"sni":  serviceJson["sni"],
					"alpn": serviceJson["alpn"],
					"host": serviceJson["host"],
					"path": serviceJson["path"],
					"scy":  serviceJson["scy"],
					"fp":   serviceJson["fp"],
        };
        url = window.btoa(unescape(encodeURIComponent(JSON.stringify(d))));
        url = "vmess://"+ url;
        break;

      case "v2ray/vless":
        url = `vless://{{.user.Uuid}}@${params.host}:${params.port}?encryption=${serviceJson.encryption}&flow=${serviceJson.flow}&security=${serviceJson.security}&sni=${serviceJson.sni}&alpn=${serviceJson.alpn}&fp=${serviceJson.fp}&pbk=${serviceJson.pbk}&sid=${serviceJson.sid}&spx=${serviceJson.spx}&type=${serviceJson.type}&serviceName=${serviceJson.serviceName}&mode=${serviceJson.mode}&headerType=${serviceJson.headerType}&quicSecurity=${serviceJson.quicSecurity}&key=${serviceJson.key}&host=${serviceJson.host}&path=${serviceJson.path}&seed=${serviceJson.seed}#${params.name}`
        break;
      
      case "shadowsocks/ss2022":
        let pssswd = "{{.user.Uuid}}";
        if (serviceJson.cypher_method == "2022-blake3-aes-128-gcm") {
          pssswd = serviceJson.server_key+":"+window.btoa(unescape(encodeURIComponent(pssswd.substring(0, 16))))
        }
        if (serviceJson.cypher_method == "2022-blake3-aes-256-gcm") {
          pssswd = serviceJson.server_key+":"+window.btoa(unescape(encodeURIComponent(pssswd.substring(0, 32))))
        }

        let str = window.btoa(unescape(encodeURIComponent(serviceJson.cypher_method+":"+pssswd)))
        str=str.replace("+", "-")
        str=str.replace("/", "_")
        str=str.replace("=", "")

        url = `ss://${str}@${params.host}:${params.port}#${params.name}`
        break;

      case "trojan/trojan":
        url = `trojan://{{.user.Uuid}}@${params.host}:${params.port}?security=${serviceJson.security}&sni=${serviceJson.sni}&alpn=${serviceJson.alpn}&fp=${serviceJson.fp}&type=${serviceJson.type}&headerType=${serviceJson.headerType}&host=${serviceJson.host}#${params.name}`
        break;
    
      default:
        break;
    }
    console.log(params)
    console.log(serviceJson)
    copy_text(url);
  }

  function copy_text(text) {
      let input_dom = document.createElement('input');
      input_dom.value = text;
      document.body.appendChild(input_dom);//向页面底部追加输入框
      input_dom.select();//选择input元素
      document.execCommand("Copy");//执行复制命令
      notify('success', "复制成功")
      input_dom.remove();//删除动态创建的节点
  }
</script>